"use client";

import Button from "@/components/Button";
import ClientLoading from "@/components/ClientLoading";
import { Form, Input, Select } from "@/components/Form";
import Label from "@/components/Form/Label";
import { DELETE, GET, POST } from "@/utils/fetch";
import React, { useEffect, useState } from "react";

const defaultFrm: SubForm = {
  id: "",
  type: "v2ray",
  cfip: "",
  skip: "",
  url: "",
  includeOrgin: false,
};

export default function SubUI() {
  // const [id, setId] = useState<string>("");
  const [cfips, setCfips] = useState<Cfip[]>([]);

  const [data, setData] = useState({
    ...defaultFrm,
    // id,
    // cfip: cfips[0]?.code || "",
  });
  const [isLoading, setLoading] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      const subResp: JsonResp<Sub> = await GET("/sub");
      if (subResp.code !== 0) {
        throw new Error(subResp.msg);
      }
      // setData({ ...data,  });

      const cfipResp: JsonResp<Cfip[]> = await GET("/cfip");
      if (cfipResp.code !== 0) {
        throw new Error(cfipResp.msg);
      }
      const tmpCfips = [...cfipResp.data];
      setCfips([...tmpCfips]);
      setData({ ...data, cfip: tmpCfips[0]?.code || "", id: subResp.data.id });
    };
    setLoading(true);
    fetchData()
      .catch((e) => {
        alert((e as Error).message);
        console.log(e);
      })
      .finally(() => setLoading(false));
  }, []);

  const changeValue =
    (key: string) =>
    (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
      const v = e.target.value.trim();
      setData({ ...data, [key]: v });
    };

  const reid = async () => {
    setLoading(true);
    try {
      const delResp: JsonResp<any> = await DELETE("/sub");
      if (delResp.code !== 0) {
        throw new Error(delResp.msg);
      }

      const resp: JsonResp<Sub> = await POST("/sub", {});
      if (resp.code !== 0) {
        throw new Error(resp.msg);
      }

      setData({ ...data, id: resp.data.id });
    } catch (e) {
      alert((e as Error).message);
      console.log(e);
    } finally {
      setLoading(false);
    }
  };

  const genUrl = () =>
    `${process.env.NEXT_PUBLIC_SUB_URL}/${data.id}?t=${data.type}&cf=${
      data.cfip
    }&s=${data.skip}&o=${data.includeOrgin ? "1" : "0"}`;

  const copyUrl = async () => {
    try {
      await navigator.clipboard.writeText(genUrl());
      alert("复制成功");
    } catch (e) {
      alert("复制失败");
      console.log(e);
    }
  };

  return (
    <>
      {isLoading && <ClientLoading />}
      <Form includeCancel={false} includeOk={false}>
        <div className="flex flex-col gap-y-1">
          <Label label="订阅ID">{data.id}</Label>
          <Button
            size="sm"
            color="info"
            onClick={async (e) => {
              if (!window.confirm("确定要重新生成订阅ID吗？")) {
                return e.preventDefault();
              }
              await reid();
            }}
          >
            重新生成
          </Button>
        </div>
        <Select
          items={[
            { value: "v2ray", label: "v2ray" },
            { value: "clash", label: "clash" },
          ]}
          label="订阅类型"
          value={data.type}
          onChange={changeValue("type")}
        ></Select>
        <Select
          items={cfips.map((cf) => ({ label: cf.name, value: cf.code }))}
          label="优选IP"
          value={data.cfip}
          onChange={changeValue("cfip")}
        ></Select>
        <Input label="过滤" value={data.skip} onChange={changeValue("skip")} />
        <div className="block">
          <div className="mt-2">
            <div>
              <label className="inline-flex items-center">
                <input
                  type="checkbox"
                  checked={data.includeOrgin}
                  onChange={(e) => {
                    setData({ ...data, includeOrgin: e.target.checked });
                  }}
                />
                <span className="ml-2">包含原始节点</span>
              </label>
            </div>
          </div>
        </div>
        <div className="flex flex-col gap-y-1">
          <Label label="订阅地址" onDoubleClick={copyUrl}>
            {genUrl()}
          </Label>
          <Button size="sm" color="primary" onClick={copyUrl}>
            复制
          </Button>
        </div>
      </Form>
    </>
  );
}
